/**
 * @file select
 * @author liaoxuezhi@baidu.com
 *
 * https://github.com/JedWatson/react-select
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import * as assign from 'object-assign';
import * as cx from 'classnames';
import Uplader from '../../../widgets/uploader/image';

// @require 'react-select/dist/react-select.css';
// jest 不能支持这种写法
// import 'react-select/dist/react-select.css';

import {Enhance as FormItem} from '../form-item';
import {filter} from '../../util';

@FormItem({
  type: 'image',
  validate() {
    const input = this.input;

    if (input && input.state.locked && this.isFormSubmitted()) {
      return input.state.lockMsg || `图片上传处理中，请稍候`;
    }

    if (input && input.state.onFormItemValid) {
      let fn = input.state.onFormItemValid;
      input.setState({
        onFormItemValid: null,
      }, () => setTimeout(fn, 200));
    }

    return true;
  },
  validateSchema: 'http://amis.baidu.com/schemas/form.json#/definitions/formItem'
})
export default class ImageUploader extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    formMode: PropTypes.string,
    formHorizontal: PropTypes.object,
    joinValues: PropTypes.bool.isRequired,
    delimiter: PropTypes.string.isRequired,
    // canDelete: PropTypes.bool,
    maxSize: PropTypes.number,
    multiple: PropTypes.bool, // 是否可多选
    maxLength: PropTypes.number, // 最多能选多少个？
    autoUpload: PropTypes.bool // 是否自动上传
  };

  static defaultProps = {
    value: '',
    placeholder: '将图片拖入该区域，或者',
    joinValues: true,
    delimiter: ',',
    reciever: '/api/image',
    compress: "auto",
    showCompressOptions: false,
    allowInput: false,
    compressOptions: {
    },
    // canDelete: true,
    multiple: false,
    maxLength: 0,
    maxSize: 0,
    autoUpload: true,
    hideUploadButton: false
  };

  constructor(props) {
    super(props);
    this.changeValue = this.changeValue.bind(this);
    this.handleLock = this.handleLock.bind(this);
    this.handleUnLock = this.handleUnLock.bind(this);

    this.state = {
      locked: false,
      fromInput: false,
      files: this.value2files(props.formItemValue, props)
    };
  }

  componentWillReceiveProps(nextProps) {
    const props = this.props;

    if (props.formItemValue !== nextProps.formItemValue) {
      this.setState({
        files: this.value2files(nextProps.formItemValue, nextProps)
      });
    }
  }

  onSubmit(model, component, form) {
    const input = this;

    if (input.state.locked) {
      form.validate(component);

      if (input.state.unlockFn) {
        let fn = input.state.unlockFn;
        input.setState({
          unlockFn: null,
          onFormItemValid: () => form.submit()
        }, () => fn((error) => error || setTimeout(form.submit, 200)));
      }

      return false;
    }
  }

  value2files(value, props) {
    const {joinValues, multiple, delimiter} = props;

    if (multiple && joinValues && typeof value === 'string') {
      value = value.split(delimiter);
    }

    return value;
  }

  changeValue(newValue) {
    const {
      joinValues,
      delimiter,
      multiple
    } = this.props;

    if (joinValues) {
      if (multiple) {
        newValue = newValue && newValue.map(item => item.url).join(delimiter);
      } else {
        newValue = newValue && newValue.value;
      }
    }

    this.props.setValue(newValue);
  }

  handleLock(unlockFn, lockMsg) {
    this.setState({locked: true, validateFlag: true, unlockFn, lockMsg});
  }

  handleUnLock() {
    this.setState({locked: false, unlockFn: null});
  }

  render() {
    const {
      name,
      placeholder,
      disabled,
      reciever,
      crop,
      limit,
      compress,
      showCompressOptions,
      compressOptions,
      allowInput,
      maxLength,
      maxSize,
      // canDelete,
      multiple,
      autoUpload,
      data,
      accept,
      hideUploadButton
    } = this.props;

    const {
      locked,
      fromInput
    } = this.state;
    let value = this.props.getValue();


    const selectProps = {
      name, placeholder,
      autosize: false,
      value: this.state.files,
      onChange: (value) => {
        this.changeValue(value);
        this.setState({
          fromInput: false
        });
      },
      disabled,
      reciever: filter(reciever, data),
      crop,
      limit,
      compress,
      compressOptions,
      showCompressOptions,
      onRequestLock: this.handleLock,
      onRequestUnLock: this.handleUnLock,
      // canDelete,
      multiple,
      maxSize,
      maxLength,
      autoUpload,
      hideUploadButton,
      accept
    };

    return (
      <div>
        {!value || !fromInput ? (
          <Uplader
            key="input"
            {...selectProps}
          />
        ) : null}

        {allowInput && !multiple && (!value || fromInput) ? (
          <input
            type="text"
            className="form-control m-t"
            placeholder="允许直接设置图片地址"
            disabled={disabled || locked}
            value={value || ''}
            onChange={e => {
              this.changeValue({url: e.currentTarget.value});
              this.setState({
                fromInput: true
              });
            }}
          />
        ) : null}
      </div>
    );
  }
}
